package com.sync.data.common.interceptor;

import cn.hutool.core.util.ClassUtil;

import com.sync.data.common.obj.ObjectNo;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * @author liquanchang
 */
@Component
public class CommonIdGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {

        Class<?> objClass = obj.getClass();

        // 获取实体类的主键字段
        Field field = ReflectionUtils.findField(objClass, "id");
        if (field == null) {
            throw new HibernateException("No primary key found for entity: " + objClass.getName());
        }

        // 获取主键字段的值
        Object idValue = ReflectionUtils.getField(field, obj);
        if (idValue != null) {
            // 如果主键字段的值不为空，则直接返回它作为主键值
            return (Serializable) idValue;
        } else {
            // 如果主键字段的值为空，则生成一个新的主键值
            // 这边的主键生成规则为对象编号+纳秒
            return ObjectNo.objectNo(ClassUtil.getClassName(obj,true))+System.nanoTime();
        }
    }
}
